var express = require('express');
var router = express.Router();
const shsDB = require("./../../db/index.js");

let mgcWordObj = {
	value: "", //敏感词
	code: "sensitiveWords", //敏感词字典名称code
	time: new Date().getTime() //有效时间
};

router.post("/handle", function(req, res) {
	let obj = {
		code: 201,
		message: "success",
		status: false, //false不存在敏感词
		highlightedText: "", //高亮
	}
	let contentText = req.body.value
	if (contentText == undefined) {
		obj.message = "参数不合法"
		res.send(JSON.stringify(obj))
		return
	}
	
	if (mgcWordObj.time < new Date().getTime()) {
		let sql = `select * from dict where code='${mgcWordObj.code}'`;
		shsDB(sql).then(data => {
			obj.code = 200
			mgcWordObj.time = new Date().getTime() + 2 * 60 * 60 * 1000; //俩小时
			let item = data[0] && data[0].value || "";
			if (data.length && item) {
				mgcWordObj.value = item.split(',') || []
			}

			try {
				mgcWordObj.value.forEach(word => {
					const regex = new RegExp(`(${word})`, 'gi');
					if (regex.test(contentText)) {
						obj.status = true;
						obj.highlightedText = contentText.replace(regex,
							'<span style="color: red;">$1</span>');
					}
					
					if (obj.status) {
						throw new Error("find");
					}
				});
				res.send(JSON.stringify(obj))
			} catch (error) {
				res.send(JSON.stringify(obj))
			}
		})
	} else {
		try {
			obj.code = 200
			mgcWordObj.value.forEach(word => {
				const regex = new RegExp(`(${word})`, 'gi');
				if (regex.test(contentText)) {
					obj.status = true;
					obj.highlightedText = contentText.replace(regex,
						'<span style="color: red;">$1</span>');
				}
				if (obj.status) {
					throw new Error("find");
				}
			});
			res.send(JSON.stringify(obj))
		} catch (error) {
			res.send(JSON.stringify(obj))
		}
	}


})
module.exports = router;